package org.mspring.mlog.web.security.remember;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.common.Keys;
import org.mspring.mlog.core.ServiceFactory;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.web.security.UserDetailsImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 
 * @author Gao Youbo
 * @since 2013年7月26日
 */
@SuppressWarnings("deprecation")
public class TokenBasedRememberMeServices extends org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices {

    @Override
    protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        UserDetails userDetails = super.processAutoLoginCookie(cookieTokens, request, response);
        if (userDetails != null) {
            setSessionUser(userDetails, request);
        }
        return userDetails;
    }

    /**
     * 将User对象保存到Session中
     * 
     * @param userDetails
     * @param request
     */
    protected void setSessionUser(UserDetails userDetails, HttpServletRequest request) {
        User user = null;
        String username = userDetails.getUsername();
        if (userDetails instanceof UserDetailsImpl) {
            UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userDetails;
            user = userDetailsImpl.getUserEntity();
            if (user == null) {
                user = ServiceFactory.getUserService().getUserByName(username);
            }
        } else {
            user = ServiceFactory.getUserService().getUserByName(username);
        }
        request.getSession().setAttribute(Keys.CURRENT_USER, user);
    }

    @Override
    protected String retrievePassword(Authentication authentication) {
        // TODO Auto-generated method stub
        if (authentication.getPrincipal() instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) authentication.getPrincipal()).getPassword();
        } else {
            if (authentication.getCredentials() == null) {
                return null;
            }
            return authentication.getCredentials().toString();
        }
    }

}
